import time
import hmac
import hashlib
import base64
import urllib.parse

import requests


def generate_sign():
    timestamp = str(round(time.time() * 1000))
    secret = 'SEC1a0a1c96f6e3ce4a8cbe7d148c9694c66f5ae565e166233f852c695d8485a954'
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    print(timestamp)
    print(sign)
    return  timestamp,sign

def  send_dingding_msg(content,at_all=True):
        timestamp_sign=generate_sign()
        #首先需要拿到丁丁机器人的webhook地址+timestamp+sign拼接成一个完整的地址
        url=f'https://oapi.dingtalk.com/robot/send?access_token=a54819092991581c9be62057136e9efdf2f8f85195c15c389c1d8c342aa08913&timestamp={timestamp_sign[0]}&sign={timestamp_sign[1]}'
        headers={'Content_type':'application/json;charset=utf-8'}
        req_data={
            'msgtype':'text',
            'text':{
                'content':content
            },
        'at':{
            'isAtall':at_all
            }
        }
        res=requests.post(url=url,json=req_data,headers=headers)
        return   res.text
        print(url)

if __name__=='__main__':
    content='''
    各位好，本次电商项目的测试报告执行结果如下：
    测试用例总共：110
    通过：100
    失败：3
    跳过：4
    异常：7
    '''
    text=send_dingding_msg(content=content)
    print(text)

